import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { LeaveRoomMessageData } from "../types/MessageData";

export const leaveRoomHandler = ({ user, payload, client }: { client: WebSocket; user: User; payload: LeaveRoomMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	if (room) {
		const index = room.players.findIndex((player) => player.user.userId == user.userId);
		if (index != -1) room.players.splice(index, 1);
		[client, ...room.players.map((v) => v.client)].forEach((v) => v!.send(conversionMessage({ type: "leftRoom", payload: { roomId: room.roomId, userId: user.userId } })));
		const log = { userId: user.userId, username: user.username, log: "退出了房间。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
